import { defineStore } from 'pinia';
import { store } from '@/store';
import type { UserInfo } from '@/types/interface';

const InitUserInfo: UserInfo = {
  name: '', // 用户名
  roles: [], // 权限
};

export const useUserStore= defineStore('user', {
  state: () => ({
   token:"",
   userInfo: { ...InitUserInfo },
  }),
  actions: {
    async login(userInfo: Record<string, unknown>) {
      const mockLogin = async (userInfo: Record<string, unknown>) => {
        // 登录请求流程
        console.log(`用户信息:`, userInfo);
        return {
          code: 200,
          message: '登录成功',
          data: 'main_token',
        };
      };

      const res = await mockLogin(userInfo);
      if (res.code === 200) {
        this.token = res.data;
      } else {
        throw res;
      }
    },
    async getUserInfo() {
      const mockRemoteUserInfo = async (token: string) => {
        if (token === 'main_token') {
          return {
            name: 'Codesigner-admin',
            roles: ['all'], 
          };
        }
        return {
          name: 'Codesigner-normal',
          roles: ['normal'], 
        };
      };
      const res = await mockRemoteUserInfo(this.token);

      this.userInfo = res;
    },
    async logout() {
      this.token = '';
      this.userInfo = { ...InitUserInfo };
    },
  },
  persist: true
});

export function getUserStore() {
  return useUserStore(store);
}